package org.campuscontent.io;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.campuscontent.ui.AutomataGraph;

public class AutomataExporter
{
	private AutomataExporter()
	{
	}

	public static AutomataExporter getInstance()
	{
		return self;
	}

	public void saveAutomataGraph(AutomataGraph graph, String filename)
	{
		try
		{
			int width = graph.getWidth();
			int height = graph.getHeight();

			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2 = image.createGraphics();
			graph.paint(g2);
			g2.dispose();

			try
			{
				ImageIO.write(image, "png", new File(filename));
			} catch (IOException ioe)
			{
				System.out.println(ioe.getMessage());
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public String getAutomataImageEncoded(AutomataGraph graph)
	{
		String str = null;
		try
		{
			int width = graph.getWidth();
			int height = graph.getHeight();

			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2 = image.createGraphics();
			graph.paint(g2);
			g2.dispose();

			try
			{
				ByteArrayOutputStream out = new ByteArrayOutputStream();

				ImageIO.write(image, "png", out);
				byte[] buf = out.toByteArray();
			
				buf = Base64.encode(buf);
				str = new String(buf);
				return str;
			} catch (IOException ioe)
			{
				System.out.println(ioe.getMessage());
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return str;
	}

	private static final AutomataExporter self = new AutomataExporter();
}
